/**
 *
 */
package org.insia.smartposse.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.insia.smartposse.form.JobForm;
import org.insia.smartposse.manager.JobProjectManager;
import org.insia.smartposse.manager.ProjectManager;
import org.insia.smartposse.manager.list.SkillMapManager;

/**
 * @author cmougel
 *
 */
public class JobAction extends DispatchAction {


	/**
	 * View the form to add a Job to a project
	 *
	 * @param map
	 * @param form
	 * @param req
	 * @param resp
	 * @return
	 * @throws Exception
	 */
	public ActionForward viewForm(ActionMapping map, ActionForm form, HttpServletRequest req, HttpServletResponse resp) throws Exception {

		// Check if the Project Exist
		ProjectManager proMan = new ProjectManager(new Integer(req.getParameter("id")));

		if (null == proMan.getProject()){
			resp.setStatus(404);
			return null;
		}

		// Init the Form
		JobForm jobForm = (JobForm) form;
		jobForm.setProjectId(new Integer(req.getParameter("id")));

		// Fill attribute
		req.setAttribute("addjob", true);
		req.setAttribute("project", proMan);
		req.setAttribute("skillMap", new SkillMapManager().getMap());

		return map.findForward("addjob");
	}

	/**
	 * Save the Job for the Project
	 *
	 * @param map
	 * @param form
	 * @param req
	 * @param resp
	 * @return
	 * @throws Exception
	 */
	public ActionForward createjob(ActionMapping map, ActionForm form, HttpServletRequest req, HttpServletResponse resp) throws Exception {

		// Save the Form
		new JobProjectManager((JobForm) form).save();

		//Redirect to view Project
		resp.sendRedirect(req.getContextPath() + "/project.do?cmd=view&id=" + ((JobForm) form).getProjectId());
		return null;
	}

	/**
	 * Define the default method
	 */
	@Override
	protected ActionForward dispatchMethod(ActionMapping map, ActionForm form, HttpServletRequest req, HttpServletResponse resp, String name) throws Exception {

		if (null == name || name.equals("")){
			return viewForm(map, form, req, resp);
		} else {
			return super.dispatchMethod(map, form, req, resp, name);
		}
	}

}
